package com.hula.init;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuhe
 * @date 2021/3/25
 * @Description 初始化公钥私钥
 */
public class InitRSASecret {
    private static final String KEY_ALGORITHM = "RSA";
    public static final String PUBLIC_KEY = "rsa_public_key";
    public static final String PRIVATE_KEY = "rsa_private_key";

    /**
     * 初始化公钥私钥
     */
    public static Map<String, String> initKey(){
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            // 初始化
            keyPairGen.initialize(1024);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // 公钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            // 私钥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            Map<String, String> keyMap = new HashMap<>(2);
            keyMap.put(PUBLIC_KEY, Base64.getEncoder().encodeToString(publicKey.getEncoded()));
            keyMap.put(PRIVATE_KEY, Base64.getEncoder().encodeToString(privateKey.getEncoded()));
            return keyMap;
        } catch (NoSuchAlgorithmException e) {
           throw new RuntimeException("初始化秘钥失败:" +  e.getMessage());
        }
    }

    public static void getFile() {
        String privateKey = "";
        String lineSeparator = System.getProperty("line.separator", "\n");
        OutputStreamWriter writer;
        try {
            final FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/b.txt"));
            writer = new OutputStreamWriter(fileOutputStream);
            writer.write("-----BEGIN RSA PRIVATE KEY-----" + lineSeparator);
            int count = 64;
            int i = 0;
            while (i < privateKey.length()) {
                int max = i + count;
                writer.write(privateKey.substring(i, Math.min(max, privateKey.length())) + lineSeparator);
                i += count;
            }
            writer.write("-----END RSA PRIVATE KEY-----" );
            writer.flush();
            writer.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        getFile();
    }
}
